package de.dopichaj.labrador.tools;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;

import de.dopichaj.labrador.index.Index;
import de.dopichaj.labrador.index.IndexVersionException;
import de.dopichaj.labrador.index.TagFactory;
import de.dopichaj.labrador.index.meta.BaselineDocumentMetaDataFactory;
import de.dopichaj.labrador.index.meta.DocumentMetaData;
import de.dopichaj.labrador.index.meta.HitFactory;
import de.dopichaj.labrador.index.meta.HitFactory.DigestCollector;
import de.dopichaj.labrador.index.own.OwnFileSystemIndex;
import de.dopichaj.labrador.search.hit.Hit;
import de.dopichaj.labrador.search.hit.HitHierarchyTree;


public final class DigestStats {

    private static final class Collector implements DigestCollector {

        private int maxK = 0;
        private int documentCount = 0;
        private long elementCount = 0;
        private int elementNameCountSum = 0;
        private long documentLengthSum = 0;
        private final Set<String> globalKnownNames = new HashSet<String>();
        private final Map<String, Integer> tagDist = new HashMap<String, Integer>();
        
        public void collectDigest(DocumentMetaData digest) {
            
            documentCount++;
            final Collection<Hit> hits = digest.getFragments().values();
            
            elementCount += hits.size();
            
            elementNameCountSum += countElementNames(hits);
            
            final HitHierarchyTree tree = new HitHierarchyTree(hits);
            
            final Hit root = tree.getRoot();
            
            documentLengthSum += root.getContentLength();
            
            calculateMaxK(tree, root);
        }

        private int countElementNames(Collection<Hit> hits) {
            final Set<String> knownNames = new HashSet<String>();
            
            for (final Hit hit : hits) {
                final String markup = hit.getMarkup();
                knownNames.add(markup);
                globalKnownNames.add(hit.getMarkup());
                if (tagDist.containsKey(markup)) {
                    tagDist.put(markup, tagDist.get(markup) + 1);
                } else {
                    tagDist.put(markup, 1);
                }
            }
            
            return knownNames.size();
        }

        private void calculateMaxK(HitHierarchyTree tree, Hit root) {
            
            final SortedSet<Hit> children = tree.getChildren(root);
            final int k = children.size();
            if (k > maxK) {
                maxK = k;
            }
            
            for (final Hit child : children) {
                calculateMaxK(tree, child);
            }
        }
        
        public int getMaxK() {
            return maxK;
        }
        
        public double getMeanElementNameCount() {
            return (double)elementNameCountSum / documentCount;
        }
        
        public double getMeanDocumentLengh() {
            return (double)documentLengthSum / documentCount;
        }

        public int getDocumentCount() {
            return documentCount;
        }
        
        public long getElementCount() {
            return elementCount;
        }
        
        public int getElementNameCount() {
            return globalKnownNames.size();
        }
        
        public Map<String, Integer> getTagDist() {
            return tagDist;
        }
    }
    
    /**
     * @param args
     * @throws IOException 
     * @throws FileNotFoundException 
     * @throws IndexVersionException 
     */
    public static void main(String[] args) throws FileNotFoundException, IOException, IndexVersionException {
        
        // open the de.dopichaj.labrador.index
        final Index index = new OwnFileSystemIndex(new File(args[0]));
        final TagFactory tagFactory = index.getTagFactory();
        final Collector collector = new Collector();
        
        HitFactory.readDigests(new BaselineDocumentMetaDataFactory(index.getIOFactory()), tagFactory,
            index.getDigestByteReader(), collector);
        
        System.err.println("Document count: " + collector.getDocumentCount());
        System.err.println("Mean element count: " + collector.getElementCount());
        System.err.println("Distinct element names: " + collector.getElementNameCount());
        System.err.println("k=" + collector.getMaxK());
        System.err.println("Mean element name count: " + collector.getMeanElementNameCount());
        System.err.println("Mean document length: " + collector.getMeanDocumentLengh());
        
        final Map<String, Integer> tagDist = collector.getTagDist();
        for (final Map.Entry<String, Integer> entry : tagDist.entrySet()) {
            System.out.println(entry.getValue() + "\t" + entry.getKey() + "\t" + tagFactory.getTag(entry.getKey()));
        }
    }

}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/